<?php

namespace App\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use App\Models\ClassModel;
use Illuminate\Http\Request;
use App\Models\ClassStudentModel;
use App\Models\StudentCourseModel;
use Illuminate\Support\Facades\DB;
use App\Services\ClassService;

class ClassStudentController extends Controller
{
    public function page(Request $request){
        $query = DB::table('class_student as cs')
            ->leftJoin('class as c', 'cs.class_id', '=', 'c.id')
            ->leftJoin('student as s', 'cs.student_id', '=', 's.id')
            ->leftJoin('class_course as cc', function($join) {
                $join->on('cc.class_id', '=', 'cs.class_id')
                    ->on('cc.course_id', '=', 'cs.course_id');
            })
            ->select('cs.*', 'c.name as class_name', 'cc.course_name', 's.name as student_name')
            ->where('c.company_id', $request->company_id)
            ->whereNull('cs.deleted_at');
        
        if ($request->classId)
            $query->where('cs.class_id', $request->classId);

        if ($request->studentId)
            $query->where('cs.student_id', $request->studentId);

        $data = $query->paginate($request->per_page ?? 10, ['*'], 'page', $request->page?? 1);
        return self::ok($data);
    }

    public function add(Request $request){
        // 检查是否已经存在
        $filter = [
            'class_id' => $request->class_id,
            'student_id' => $request->student_id,
            'course_id' => $request->course_id,
        ];

        if (ClassStudentModel::where($filter)->first()) {
            return self::err('该学生已存在');
        }

        // 检查班级人数是否超过限制
        $class = ClassModel::find($request->class_id);
        if ($class->total_num >= $class->max_num) {
            return self::err('班级人数已满');
        }

        // 检查学员是否已经购买了该班级的课程
        $hasBuyCourse = StudentCourseModel::where('student_id', $request->student_id)
            ->where('course_id', $request->course_id)->first();
        if (!$hasBuyCourse) {
            return self::err('该学员未购买该课程');
        }
        
        $classStudent = new ClassStudentModel();
        $classStudent->fill($filter);
        $classStudent->save();

        // 更新班级的学生数量
        $class->total_num += 1;
        $class->save();
        return self::ok();
    }
    public function delete(Request $request){
        $classStudent = ClassStudentModel::find($request->id);
        if(!$classStudent){
            return self::err('数据不存在');
        }
        
        ClassService::removeStudent($classStudent->student_id, $classStudent->class_id);
        return self::ok();
    }
}
